package com.sdr.hkcamera;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.hik.mcrsdk.rtsp.LiveInfo;
import com.hik.mcrsdk.rtsp.RtspClient;
import com.hikvision.vmsnetsdk.CameraInfoEx;
import com.hikvision.vmsnetsdk.RealPlayURL;
import com.hikvision.vmsnetsdk.ServInfo;
import com.hikvision.vmsnetsdk.VMSNetSDK;
import com.hikvision.vmsnetsdk.netLayer.msp.deviceInfo.DeviceInfo;
import com.sdr.hkcamera.data.TempData;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * Created by homelajiang on 2016/10/21 0021.
 */

public class HKCameraActivity extends AppCompatActivity implements LiveCallBack
        , SurfaceHolder.Callback {

    public static final String CAMERA_ID = "camera_id";
    ProgressBar progressBar;
    ImageView add;
    ImageView del;
    SurfaceView surfaceView;
    ImageView retry;

    ImageView btnLeftUp;
    ImageView btnUp;
    ImageView btnRightUp;
    ImageView btnLeft;
    ImageView btnStop;
    ImageView btnRight;
    ImageView btnLeftDown;
    ImageView btnDown;
    ImageView btnRightDown;
    ImageView btnVideo;
    ImageView btnPhoto;
    ImageView btnSpeaker;
    ImageView btnZoomOut;
    ImageView btnZoomIn;
    ImageView btnNear;
    ImageView btnFar;

    private VMSNetSDK mVmsNetSDK;
    private RtspClient mRtspHandle;
    private String cameraId;
    private LiveControl liveControl;

    private final Handler mMessageHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case ConstantLive.RTSP_SUCCESS:
/*                    Toast.makeText(HKCameraActivity.this, "启动取流成功", Toast.LENGTH_SHORT).show();*/
                    break;

                case ConstantLive.STOP_SUCCESS:
/*                    Toast.makeText(HKCameraActivity.this, msg.what + "停止成功", Toast.LENGTH_SHORT).show();*/
//                    add.setVisibility(View.VISIBLE);
//                    del.setVisibility(View.GONE);
                    break;

                case ConstantLive.START_OPEN_FAILED:
                    Toast.makeText(HKCameraActivity.this, "开启播放库失败", Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                    retry.setVisibility(View.VISIBLE);
//                    add.setVisibility(View.VISIBLE);
//                    del.setVisibility(View.GONE);
                    liveControl.stop();
                    break;

                case ConstantLive.PLAY_DISPLAY_SUCCESS:
/*                    Toast.makeText(HKCameraActivity.this, msg.what + "播放成功", Toast.LENGTH_SHORT).show();*/
                    progressBar.setVisibility(View.GONE);
//                    del.setVisibility(View.VISIBLE);
                    break;

                case ConstantLive.RTSP_FAIL:
                    Toast.makeText(HKCameraActivity.this, "RTSP链接失败", Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                    retry.setVisibility(View.VISIBLE);
//                    add.setVisibility(View.VISIBLE);
//                    del.setVisibility(View.GONE);

                    liveControl.stop();
                    break;

                case ConstantLive.GET_OSD_TIME_FAIL:
                    Toast.makeText(HKCameraActivity.this, "获取OSD时间失败", Toast.LENGTH_SHORT).show();
                    break;

                case ConstantLive.SD_CARD_UN_USEABLE:
                    Toast.makeText(HKCameraActivity.this, "SD卡不可用", Toast.LENGTH_SHORT).show();
                    break;

                case ConstantLive.SD_CARD_SIZE_NOT_ENOUGH:
                    Toast.makeText(HKCameraActivity.this, "SD卡空间不足", Toast.LENGTH_SHORT).show();
                    break;
                case ConstantLive.CAPTURE_FAILED_NPLAY_STATE:
                    Toast.makeText(HKCameraActivity.this, "非播放状态不能抓拍", Toast.LENGTH_SHORT).show();
                    break;
                case ConstantLive.RECORD_FAILED_NPLAY_STATE:
                    Toast.makeText(HKCameraActivity.this, "非播放状态不能录像", Toast.LENGTH_SHORT).show();
                    break;
                case ConstantLive.AUDIO_START_FAILED_NPLAY_STATE:
                    Toast.makeText(HKCameraActivity.this, "非播放状态不能开启音频", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private ServInfo mServInfo;
    private String serAddr;
    private String sessionid;
    private CameraInfoEx cameraInfoEx;
    private boolean mIsRecord;
    private boolean mIsAudioOpen;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getResources().getIdentifier("camera_info", "layout", getPackageName()));
        mVmsNetSDK = VMSNetSDK.getInstance();
//        mVmsNetSDK.openLog(true);
        mRtspHandle = RtspClient.getInstance();

        mServInfo = TempData.getInstance().getLoginData();
        serAddr = TempData.getInstance().getServerAddr();
        sessionid = mServInfo.getSessionID();

        cameraId = getIntent().getStringExtra(CAMERA_ID);
        liveControl = new LiveControl(999);
        liveControl.setLiveCallBack(this);
        initView();
    }

    private void initView() {

        if (getSupportActionBar() != null){
            getSupportActionBar().setTitle("摄像头控制");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        add = (ImageView) findViewById(getResources().getIdentifier("add", "id", getPackageName()));
        del = (ImageView) findViewById(getResources().getIdentifier("del", "id", getPackageName()));
        retry = (ImageView) findViewById(getResources().getIdentifier("retry", "id", getPackageName()));
        surfaceView = (SurfaceView) findViewById(getResources().getIdentifier("surfaceView", "id", getPackageName()));
        progressBar = (ProgressBar) findViewById(getResources().getIdentifier("progressBar", "id", getPackageName()));

        add.setVisibility(View.GONE);
        del.setVisibility(View.GONE);

        btnLeftUp = (ImageView) findViewById(getResources().getIdentifier("left_up", "id", getPackageName()));
        btnUp = (ImageView) findViewById(getResources().getIdentifier("up", "id", getPackageName()));
        btnRightUp = (ImageView) findViewById(getResources().getIdentifier("right_up", "id", getPackageName()));
        btnLeft = (ImageView) findViewById(getResources().getIdentifier("left", "id", getPackageName()));
        btnStop = (ImageView) findViewById(getResources().getIdentifier("stop", "id", getPackageName()));
        btnRight = (ImageView) findViewById(getResources().getIdentifier("right", "id", getPackageName()));
        btnLeftDown = (ImageView) findViewById(getResources().getIdentifier("left_down", "id", getPackageName()));
        btnDown = (ImageView) findViewById(getResources().getIdentifier("down", "id", getPackageName()));
        btnRightDown = (ImageView) findViewById(getResources().getIdentifier("right_down", "id", getPackageName()));
        btnVideo = (ImageView) findViewById(getResources().getIdentifier("take_video", "id", getPackageName()));
        btnPhoto = (ImageView) findViewById(getResources().getIdentifier("take_photo", "id", getPackageName()));
        btnSpeaker = (ImageView) findViewById(getResources().getIdentifier("speaker", "id", getPackageName()));
        btnZoomOut = (ImageView) findViewById(getResources().getIdentifier("zoom_out", "id", getPackageName()));
        btnZoomIn = (ImageView) findViewById(getResources().getIdentifier("zoom_in", "id", getPackageName()));
        btnNear = (ImageView) findViewById(getResources().getIdentifier("near", "id", getPackageName()));
        btnFar = (ImageView) findViewById(getResources().getIdentifier("far", "id", getPackageName()));

        retry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(cameraId))
                    return;
                progressBar.setVisibility(View.VISIBLE);
                retry.setVisibility(View.GONE);
                new CameraAsyncTask().execute();
            }
        });

        btnLeftUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(11);
            }
        });
        btnUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(1);
            }
        });
        btnRightUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(12);
            }
        });
        btnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(3);
            }
        });
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopCloudCtrl();
            }
        });
        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(4);
            }
        });
        btnLeftDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(13);
            }
        });
        btnDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(2);
            }
        });
        btnRightDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(14);
            }
        });
        btnVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recordBtnOnClick();
            }
        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                captureBtnOnClick();
            }
        });
        btnSpeaker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                audioBtnOnClick();
            }
        });
        btnZoomOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(8);
            }
        });
        btnZoomIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(7);
            }
        });
        btnNear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(9);
            }
        });
        btnFar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCtrlCmd(10);
            }
        });

        surfaceView.getHolder().addCallback(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home)
            finish();
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onMessageCallback(int message, int index) {
        Message msg = Message.obtain();
        msg.arg1 = message;
        msg.what = index;
        mMessageHandler.sendMessage(msg);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (TextUtils.isEmpty(cameraId))
            return;
        progressBar.setVisibility(View.VISIBLE);
        retry.setVisibility(View.GONE);

        new CameraAsyncTask().execute();

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (TextUtils.isEmpty(cameraId))
            return;
        if (mIsRecord) {
            liveControl.stopRecord();
            mIsRecord = false;
        }
        liveControl.stop();
    }

    private void sendCtrlCmd(final int gestureID) {
        if (cameraInfoEx == null)
            return;
        new Thread(new Runnable() {
            @Override
            public void run() {
                int speed = 5;
                HKCameraActivity.this.mVmsNetSDK.sendStartPTZCmd(cameraInfoEx.getAcsIP(),
                        cameraInfoEx.getAcsPort(),
                        sessionid,
                        cameraId,
                        gestureID,
                        speed,
                        600,
                        String.valueOf(0));
            }
        }).start();
    }

    /**
     * 停止云台控制
     */
    private void stopCloudCtrl() {
        if (cameraInfoEx == null)
            return;
        new Thread(new Runnable() {

            @Override
            public void run() {
                String sessionID = mServInfo.getSessionID();
                HKCameraActivity.this.mVmsNetSDK.sendStopPTZCmd(cameraInfoEx.getAcsIP(),
                        cameraInfoEx.getAcsPort(),
                        sessionID,
                        cameraId, "0");
            }
        }).start();
    }

    /**
     * 抓拍 void
     *
     * @since V1.0
     */
    private void captureBtnOnClick() {
        if (null != liveControl) {
            Calendar calendar = Calendar.getInstance();
            String path = "HK_" + calendar.get(Calendar.YEAR) + "_" + (calendar.get(Calendar.MONTH) + 1)
                    + calendar.get(Calendar.DAY_OF_MONTH) + "_" + calendar.get(Calendar.HOUR_OF_DAY) +
                    calendar.get(Calendar.MINUTE) + "_" + calendar.get(Calendar.SECOND);
            boolean ret =
                    liveControl.capture(getPictureDirPath().getAbsolutePath(), "Picture" + path
                            + ".jpg");
            if (ret) {
                Toast.makeText(HKCameraActivity.this, "抓拍成功", Toast.LENGTH_SHORT).show();
            } else {

                Toast.makeText(HKCameraActivity.this, "抓拍失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void recordBtnOnClick() {
        if (null != liveControl) {
            if (!mIsRecord) {
                Calendar calendar = Calendar.getInstance();
                String path = "HK_" + calendar.get(Calendar.YEAR) + "_" + (calendar.get(Calendar.MONTH) + 1)
                        + calendar.get(Calendar.DAY_OF_MONTH) + "_" + calendar.get(Calendar.HOUR_OF_DAY) +
                        calendar.get(Calendar.MINUTE) + "_" + calendar.get(Calendar.SECOND);
                boolean ret =
                        liveControl.startRecord(getVideoDirPath().getAbsolutePath(),
                                "Video" + path
                                        + ".mp4");
                if (ret) {
                    Toast.makeText(HKCameraActivity.this, "启动录像成功", Toast.LENGTH_SHORT).show();
                    mIsRecord = true;
                } else {
                    Toast.makeText(HKCameraActivity.this, "启动录像失败", Toast.LENGTH_SHORT).show();

                }
            } else {
                liveControl.stopRecord();
                mIsRecord = false;
                Toast.makeText(HKCameraActivity.this, "停止录像成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 音频 void
     *
     * @since V1.0
     */
    private void audioBtnOnClick() {
        if (null != liveControl) {
            if (mIsAudioOpen) {
                liveControl.stopAudio();
                mIsAudioOpen = false;
                Toast.makeText(HKCameraActivity.this, "关闭音频", Toast.LENGTH_SHORT).show();
            } else {
                boolean ret = liveControl.startAudio();
                if (!ret) {
                    mIsAudioOpen = false;
                    Toast.makeText(HKCameraActivity.this, "开启音频失败", Toast.LENGTH_SHORT).show();
                } else {
                    mIsAudioOpen = true;
                    // 开启音频成功，并不代表一定有声音，需要设备开启声音。
                    Toast.makeText(HKCameraActivity.this, "开启音频成功", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

    public File getPictureDirPath() {
        File SDFile = null;
        File mIVMSFolder = null;
        try {
            SDFile = android.os.Environment.getExternalStorageDirectory();
            String path = SDFile.getAbsolutePath() + File.separator + "HIKVISION";
            mIVMSFolder = new File(path);
            if ((null != mIVMSFolder) && (!mIVMSFolder.exists())) {
                mIVMSFolder.mkdir();
                mIVMSFolder.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mIVMSFolder;
    }

    /**
     * 获取录像目录
     *
     * @return Video dir path.
     * @since V1.0
     */
    public File getVideoDirPath() {
        File SDFile = null;
        File mIVMSFolder = null;
        try {
            SDFile = android.os.Environment.getExternalStorageDirectory();
            mIVMSFolder = new File(SDFile.getAbsolutePath() + File.separator + "HIKVISION");
            if ((null != mIVMSFolder) && (!mIVMSFolder.exists())) {
                mIVMSFolder.mkdir();
                mIVMSFolder.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mIVMSFolder;
    }

    class CameraAsyncTask extends AsyncTask<Void, Void, Boolean> {

        String url;

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean ret;
            DeviceInfo deviceInfo = new DeviceInfo();

            int streamType = ConstantLive.SUB_STREAM;
            cameraInfoEx = new CameraInfoEx();
            cameraInfoEx.setId(cameraId);
            RealPlayURL mRealPlayURL = new RealPlayURL();

            ret = mVmsNetSDK.getCameraInfoEx(serAddr, sessionid, cameraId, cameraInfoEx);
            if (!ret)
                return false;

            ret = mVmsNetSDK.getDeviceInfo(serAddr, sessionid, cameraInfoEx.getDeviceId(), deviceInfo);
            if (!ret || TextUtils.isEmpty(deviceInfo.getLoginName())
                    || TextUtils.isEmpty(deviceInfo.getLoginPsw())) {
                deviceInfo.setLoginName("admin");
                deviceInfo.setLoginPsw("12345");
            }

            String mToken = mVmsNetSDK.getPlayToken(sessionid);
            LiveInfo liveInfo = new LiveInfo();
            liveInfo.setMagIp(mServInfo.getMagServer().getMagStreamSerAddr());
            liveInfo.setMagPort(mServInfo.getMagServer().getMagStreamSerPort());
            liveInfo.setCameraIndexCode(cameraInfoEx.getId());
            liveInfo.setToken(mToken);
            // 转码不区分主子码流
            liveInfo.setStreamType(streamType);
            liveInfo.setMcuNetID(mServInfo.getAppNetId());
            liveInfo.setDeviceNetID(cameraInfoEx.getDeviceNetId());
            liveInfo.setiPriority(mServInfo.getUserAuthority());
            liveInfo.setCascadeFlag(cameraInfoEx.getCascadeFlag());
            if (deviceInfo != null) {
                if (cameraInfoEx.getCascadeFlag() == LiveInfo.CASCADE_TYPE_YES) {
                    deviceInfo.setLoginName("admin");
                    deviceInfo.setLoginPsw("12345");
                }
            }
            if (mServInfo.isInternet()) {
                liveInfo.setIsInternet(LiveInfo.NETWORK_TYPE_INTERNET);
                // 获取不转码地址
                liveInfo.setbTranscode(false);
                mRealPlayURL.setUrl1(mRtspHandle.generateLiveUrl(liveInfo));

                // 获取转码地址
                // 使用默认转码参数cif 128 15 h264 ps
                liveInfo.setbTranscode(true);
                mRealPlayURL.setUrl2(mRtspHandle.generateLiveUrl(liveInfo));
            } else {
                liveInfo.setIsInternet(LiveInfo.NETWORK_TYPE_LOCAL);
                liveInfo.setbTranscode(false);
                // 内网不转码
                mRealPlayURL.setUrl1(mRtspHandle.generateLiveUrl(liveInfo));
                mRealPlayURL.setUrl2("");
            }
            url = mRealPlayURL.getUrl1();
//                    if (streamType == 2 && mRealPlayURL.getUrl2() != null && mRealPlayURL.getUrl2().length() > 0) {
//                        url = mRealPlayURL.getUrl2();
//                    }

            liveControl.setLiveParams(url,
                    deviceInfo.getLoginName(), deviceInfo.getLoginPsw());
            liveControl.startLive(surfaceView);

            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {

            if (aBoolean) {
                Log.d("asyncTask", "。。。");
            } else {
                Log.e("HKCameraAdapter", "添加摄像头获取播放地址失败");
            }
        }
    }

}
